﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics.CodeAnalysis;

namespace DomainExample.Repository
{
    public class SqlDataProvider : IDataProvider
    {
        private readonly SqlConnection _connection;

        public SqlDataProvider(IConnectionStringProvider connectionStringProvider)
        {            
            _connection = new SqlConnection(connectionStringProvider.ConnectionString);
        }

        ~SqlDataProvider()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        public IDbCommand NewCommand(string query)
        {
            return new SqlCommand(query, _connection);
        }

        public IDbDataParameter NewParameter(string name, object value)
        {
            return new SqlParameter(name, value);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                // no managed resources yet
            }

            CloseConnection();
        }

        private void CloseConnection()
        {
            if (IsConnected())
            {
                _connection.Close();
            }
        }

        private bool IsConnected()
        {
            var isConnected = _connection != null && _connection.State != ConnectionState.Closed;
            return isConnected;
        }
    }
}
